<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class UserSearchRecords extends BaseModel
{
    protected $table = "t_user_search_records";


    public static function saveRecord($user_id,$keyword,$result)
    {
        $m = new UserSearchRecords();
        $m->user_id = $user_id;
        $m->keyword = $keyword;
        $m->result = $result;
        return $m->save();
    }

    public static function getSearchResult($keyword)
    {
        $r = UserSearchRecords::where('keyword','=',$keyword)
            ->where('created_at','<=',date('Y-m-d H:i:s',time()+180))
            ->orderBy('created_at','desc')
            ->first();
        if ($r&&$r->result){
            return json_decode($r->result,true);
        }
        return false;
    }

    public static function getLike($userId)
    {
        $rows =DB::select('select result from t_user_search_records where user_id='.$userId);

        $items = [];
        foreach ($rows as $row){
            $r = json_decode($row->result,true);
            if (is_array($r)){
                $items = array_merge($items,$r);
            }
        }
        if (count($items)>0){
            $items = array_count_values($items);
            $id = array_search(max($items),$items);

            $items = WineProduct::orderBy('weight','desc')
                ->orderBy('created_at','desc')
                ->with(['userHasDrink','userWantDrink',"wineGrading","scenes",'drinkTasteKeywords'])
                ->select('id','name','chname','chateauName','vintage','banner','price','promotion_price',
                    'show_cuisine','show_scenes','letDrink_recom','grading_id')
                ->where('id','=',$id)
                ->get();
            return $items;
        }

        return [];

    }

    public static function getHotKeywords()
    {
        return DB::select('select keyword from (SELECT COUNT(id) as total,keyword FROM `t_user_search_records` GROUP BY keyword) 
          c where 1 order by total desc limit 5');
    }

}
